package com.songhq.data.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.songhq.data.bean.Response;
import com.songhq.data.bean.User;
import com.songhq.data.mapper.UserMapper;
import com.songhq.data.redis.RedisUtil;
import com.songhq.data.utils.MD5Util;
import com.songhq.data.utils.UUIDUtils;

@Service
public class UserService {
	
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RedisUtil redisUtils;

	/**
	 * 
	 * http 登入校验的规则是
	 * 
	 * 不仅要要知道你是登入状态，而且还用知道你是谁
	 * 如果用户信息已铭文的方式存在Redis中，则可能不安全，则可经过jwt加密
	 * 加密后可将数据放入
	 * 
	 * 这里没有做单点登入
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping("login")
	public Response login(String name, String password) {
		//校验该用户是否存在
		User user=userMapper.checkUser(name);
		if(user == null) {
			return Response.error(401, "用户名不存在");
		}
		String encode = MD5Util.encode(password);
		
		if(!encode.equals(user.getPassword())) {
			return Response.error(401, "密码错误");
		}
		//生成token 
		String userId = user.getUserId();
		//用户表中的userId+时间戳
		String redisKey = System.currentTimeMillis()+ userId;
		//把userId存放到redis中去
		redisUtils.set(redisKey, name, 60);
		return Response.ok(redisKey);
	}

	public void loginout(String userId) {
		//删除redis中的key 
		redisUtils.del(userId);
	}

	public Response signin(User user, String confirm) {
		//检验密码和确认密码是否一致
		String password = user.getPassword();
		if(!confirm.equals(password)) {
			return Response.error(410, "确认密码错误");
		}
		//检查用户名是否被注册过
		String name = user.getName();
		User userData=userMapper.checkUser(name);
		if(userData != null) {
			return Response.error(410, "该用户名已经被注册过");
		}
		//保存用户
		String uuid = UUIDUtils.generateUUID();
		String encodePassword = MD5Util.encode(password);
		user.setPassword(encodePassword);
		user.setUserId(uuid);
		userMapper.insert(user);
		//注册成功
		return Response.ok();
	}
	

}
